import React, { Component } from 'react';
import styles from './index.less';
import { Modal, Form, Button, Select, List, Upload, Tooltip } from 'antd';
import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer';
import VList from 'react-virtualized/dist/commonjs/List';
import PropTypes from 'prop-types';

import { TRAlert } from '#/components';
import { CloseOutlined, DownloadOutlined } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts';
import TRNotification from '#/utils/notification';
import { importContractCheckNew, importContractNew, exportExcel } from '#/services/general';

import { Debounce, downloadHandle } from '#/utils/utils';

const planIcon = 'https://10.4.6.209:8084/typeface/image/plan_icon.png';
const { Option } = Select;

class LeadingInComponent extends Component {
  static defaultProps = {
    data: [],
    otherParam: '',
    exportModel: '',
  };
  constructor(props) {
    super(props);
    this.state = {
      visible: false, //对话框是否可见
      isdisabled: true, //
      loading: false, //是否加载中
      isError: false, //是否有错
      selectIndex: -1,
      fileList: [],
      errorList: [],
    };
    this.getExEportInfoData = Debounce(this._getExEportInfoData, 1000);
  }
  componentDidMount() {
    this.setState({
      visible: true,
    });
  }
  _onCancel() {
    const { onPress } = this.props;
    this.setState(
      {
        visible: false,
      },
      () => {
        onPress({ index: 0 });
      },
    );
  }
  _onUpLoad({ fileList }) {
    var obj = {};
    obj.errorList = [];
    obj.isError = false;
    this.setState({
      fileList: fileList,
      ...obj,
    });
  }
  _onChangeSelect(value) {
    this.setState({
      selectIndex: value,
    });
  }
  _onGetParams() {
    const { data, otherParam, serviceType, importType, menuCode } = this.props;

    const { selectIndex, fileList } = this.state;
    const item = data[selectIndex];

    let other = typeof otherParam === 'object' ? otherParam : JSON.parse(otherParam);
    let otherParamData = { ...other, regionName: this.props.regionName };
    let tradOtherParam = { ...item, ...other, regionName: this.props.regionName };
    const pdata = new window.FormData();
    fileList.forEach((file) => {
      pdata.append('contractFile', file.originFileObj);
    });
    if (menuCode) {
      pdata.append('menuCode', menuCode);
    }
    if (serviceType === 5) {
      pdata.append('otherParam', otherParam);
    } else {
      pdata.append(
        'otherParam',
        serviceType === 0 || serviceType === 3
          ? JSON.stringify(tradOtherParam)
          : JSON.stringify(otherParamData),
      );
    }
    if (importType) {
      pdata.append('importType', importType);
    }
    pdata.append('serviceType', serviceType);
    return pdata;
  }

  _onError(response) {
    var obj = {};
    var errorList = [];
    if (response) {
      if (response.result.constructor == Array && response.result) {
        var list = this.state.fileList.map((item) => {
          return { ...item };
        });
        obj.fileList = list;
        obj.isError = true;
        errorList = response.result;
      } else {
        obj.isError = true;
        errorList.push(response.message || '发生未知错误,请重试');
      }
    } else {
      obj.isError = true;
      errorList.push('发生未知错误,请重试');
    }
    this.setState({ loading: false, errorList: errorList, ...obj });
  }
  async _onOk() {
    this.setState({ loading: true });
    let response = await importContractCheckNew(
      this._onGetParams(),
      this.props.importUrl,
      this.props.requestParams || {},
    );
    if (response && response.statusCode === HttpCode.SUCCESS) {
      this.setState({ loading: false });
      if (!this.props.isEs) {
        let obj = await TRAlert.warning(response.message);
        if (obj.index === 1) {
          this.setState({ loading: true });
          let res = await importContractNew(this._onGetParams(), this.props.importUrl);
          if (res && res.list !== undefined) {
            const { onPress } = this.props;
            onPress({ index: 1, data: res });
          } else {
            this._onError(res);
          }
        }
      } else {
        const { onPress } = this.props;
        onPress({ index: 1, data: response });
      }
    } else {
      this._onError(response);
    }
  }
  _onCheckDisabled() {
    const { data } = this.props;
    if (data.length > 0) {
      const { selectIndex, fileList, isError } = this.state;
      if (selectIndex >= 0 && fileList.length > 0 && !isError) {
        return false;
      }
      return true;
    } else {
      const { fileList, isError } = this.state;
      if (fileList.length > 0 && !isError) {
        return false;
      }
      return true;
    }
  }

  //下载模板
  async _getExEportInfoData() {
    try {
      let downData = this.props.exportParam;
      if (this.props.regionName) {
        downData = this.props.exportParam.map((n) => {
          return { ...n, regionName: this.props.regionName };
        });
      }
      let data = await exportExcel({
        url: this.props.url,
        exportType: this.props.exportModel,
        jsonParam: typeof downData === 'string' ? downData : JSON.stringify(downData),
      });
      if (data.data && data.data instanceof Blob) {
        const realFileName = data.response.headers.get('content-disposition').split('filename=')[1];
        downloadHandle(data.data, decodeURI(realFileName));
      } else {
        TRAlert.error(data.message);
      }
    } catch (e) {
      //TRAlert.error("下发失败",data.message)
      TRAlert.error('下载失败');
    }
  }
  //下载模板
  _onDownLoad() {
    this.getExEportInfoData();
  }
  _onErrorList() {
    if (this.state.errorList.length > 10) {
      return (
        <div style={{ height: '200px', marginTop: '10ppx' }}>
          <AutoSizer>
            {({ height, width }) => (
              <VList
                height={height}
                rowCount={this.state.errorList.length}
                rowHeight={20}
                rowRenderer={({ index, style }) => (
                  <div key={index} style={style} className={styles.listcell}>
                    {this.state.errorList[index]}
                  </div>
                )}
                width={width}
              />
            )}
          </AutoSizer>
        </div>
      );
    }
    return (
      <List
        size="small"
        style={{ marginTop: -10 }}
        header={<div className={styles.headertitle}>导入失败，原因：</div>}
        dataSource={this.state.errorList}
        renderItem={(item, index) => (
          <List.Item key={index} className={styles.listcell}>
            {item}
          </List.Item>
        )}
      />
    );
  }
  render() {
    const { selectIndex, loading, isError } = this.state;
    const { data, exportModel, title = '导入' } = this.props;
    return (
      <Modal
        width={408}
        centered={true}
        closable={false}
        okText="提交"
        cancelText="取消"
        className="modalWraps"
        maskClosable={false}
        okButtonProps={{ disabled: this._onCheckDisabled(), loading: loading }}
        visible={this.state.visible}
        onOk={this._onOk.bind(this)}
        onCancel={this._onCancel.bind(this)}
      >
        <div className={styles.row}>
          <img src={planIcon} />
          <div className={styles.content}>{title || '导入'}</div>
          <div className={styles.suffix} />
          <CloseOutlined className={styles.close} onClick={this._onCancel.bind(this)} />
        </div>
        <div className={`${styles.form} ${isError ? styles.formerror : null}`}>
          <Form layout={'vertical'}>
            {data.length > 0 ? (
              <Form.Item
                label={
                  <div className={styles.importName}>
                    <span>合约名称</span>
                    {exportModel.length > 0 ? (
                      <span onClick={this._onDownLoad.bind(this)}>下载模板</span>
                    ) : null}
                  </div>
                }
              >
                <Select
                  onChange={this._onChangeSelect.bind(this)}
                  value={selectIndex >= 0 ? selectIndex : undefined}
                  placeholder="请选择合约"
                >
                  {data.map((item, index) => {
                    return (
                      <Option value={index} key={index}>
                        <Tooltip overlayClassName="overtoop" title={item.contractName}>
                          <span>{item.contractName}</span>
                        </Tooltip>
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            ) : (
              <div className={styles.importName}>
                <span>导入文件</span>
                {exportModel.length > 0 ? (
                  <span onClick={this._onDownLoad.bind(this)}>下载模板</span>
                ) : null}
              </div>
            )}
            <Form.Item>
              <Upload
                name="logo"
                beforeUpload={() => {
                  return false;
                }}
                accept=".xls"
                fileList={this.state.fileList}
                showUploadList={{
                  showPreviewIcon: true,
                  showRemoveIcon: !loading,
                  showDownloadIcon: false,
                }}
                onChange={this._onUpLoad.bind(this)}
              >
                {this.state.fileList.length == 0 ? (
                  <Button type="primary" ghost>
                    <DownloadOutlined />
                    导入
                  </Button>
                ) : null}
              </Upload>
            </Form.Item>
          </Form>
          {this.state.errorList.length > 0 ? this._onErrorList() : null}
        </div>
      </Modal>
    );
  }
}

/*
serviceType服务Id    0：中长期合约导入  1:负荷模型导入  2:需求预测调整导入  3:购电交易方案管理导入
                   /// 4: 大群服务团队   5: 设备导入模板下载
*/
class LeadingInModal {
  __key__ = '';
  show = (data, otherParam, serviceType, exportModel, exportParam, regionName) => {
    return new window.Promise((resolve) => {
      if (this.__key__ !== '') {
        return;
      }
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <LeadingInComponent
            data={data}
            otherParam={otherParam}
            exportParam={exportParam}
            exportModel={exportModel}
            serviceType={serviceType}
            regionName={regionName}
            onPress={(reslt) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(reslt);
            }}
          />
        ),
        duration: null,
      });
    });
  };
  showEs = (params) => {
    return new window.Promise((resolve) => {
      if (this.__key__ !== '') {
        return;
      }
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <LeadingInComponent
            isEs
            url={'/eam-ledger/asset/commonExport'}
            {...params}
            importUrl={params.importUrl || '/eam-ledger/asset/excelImport'}
            onPress={(reslt) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(reslt);
            }}
          />
        ),
        duration: null,
      });
    });
  };
}
LeadingInComponent.propTypes = {
  onPress: PropTypes.func,
  data: PropTypes.array,
  otherParam: PropTypes.string,
  exportModel: PropTypes.string,
  serviceType: PropTypes.number,
  importType: PropTypes.node,
  regionName: PropTypes.node,
  exportParam: PropTypes.array,
  importUrl: PropTypes.string,
  isEs: PropTypes.node,
  url: PropTypes.string,
  menuCode: PropTypes.string,
  title: PropTypes.string,
  requestParams: PropTypes.object,
};
const leadingInModal = new LeadingInModal();
export default leadingInModal;
